﻿using System.IO;
using MyFramework.Resource;
using UnityEngine;
using MyFramework.Singleton;
using XLua;

namespace MyFramework.Lua
{
    /// <summary>
    /// lua管理器
    /// 保证lua环境的唯一性
    /// </summary>
    // ReSharper disable once ClassNeverInstantiated.Global
    public class LuaManager : Singleton<LuaManager>
    {
        /// <summary>
        /// lua虚拟环境
        /// </summary>
        private LuaEnv _luaEnv;

        /// <summary>
        /// lua中的_G
        /// </summary>
        public LuaTable Global => _luaEnv.Global;

        /// <summary>
        /// 初始化lua环境
        /// </summary>
        /// <param name="enableLuaDebugger"></param>
        public void Init(bool enableLuaDebugger)
        {
            if (_luaEnv != null)
                return;

            _luaEnv = new LuaEnv();

            if (enableLuaDebugger)
            {
                DoString(
                    "package.cpath = package.cpath .. ';C:/Users/Administrator/AppData/Roaming/Jetbrains/Rider2023.2/plugins/EmmyLua/debugger/emmy/windows/x64/emmy_core.dll'" +
                    "local dbg = require('emmy_core')" +
                    "dbg.tcpListen('localhost', 9966)" +
                    "dbg.waitIDE()" +
                    "dbg.breakHere()");
            }

            _luaEnv.AddLoader(DefaultLoader);
            _luaEnv.AddLoader(AssetBundleLoader);
        }

        private static byte[] DefaultLoader(ref string filePath)
        {
            string path = Application.dataPath + "/LuaScripts/" + filePath + ".lua";
            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }

            Debug.LogWarning("DefaultLoader重定向失败，文件名：" + filePath);
            return null;
        }

        /// <summary>
        /// 重定向加载AB包中的lua脚本
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static byte[] AssetBundleLoader(ref string filePath)
        {
            TextAsset lua = AssetBundleManager.GetInstance().LoadResource<TextAsset>("lua", filePath + ".lua");
            if (lua)
            {
                return lua.bytes;
            }

            Debug.LogWarning("MyCustomABLoader重定向失败，文件名为：" + filePath);
            return null;
        }


        /// <summary>
        /// 传入lua文件名 执行lua脚本
        /// </summary>
        /// <param name="fileName"></param>
        public void DoLuaFile(string fileName)
        {
            string str = $"require('{fileName}')";
            DoString(str);
        }

        /// <summary>
        /// 执行Lua语言
        /// </summary>
        /// <param name="str"></param>
        public void DoString(string str)
        {
            if (_luaEnv == null)
            {
                Debug.LogWarning("解析器未初始化");
                return;
            }

            _luaEnv.DoString(str);
        }

        /// <summary>
        /// 释放lua 垃圾
        /// </summary>
        public void Tick()
        {
            if (_luaEnv == null)
            {
                Debug.LogWarning("解析器未初始化");
                return;
            }

            _luaEnv.Tick();
        }

        /// <summary>
        /// 销毁解析器
        /// </summary>
        public void Dispose()
        {
            if (_luaEnv == null)
            {
                Debug.LogWarning("解析器未初始化");
                return;
            }

            _luaEnv.Dispose();
            _luaEnv = null;
        }
    }
}